package com.codeberry.yws.example;

import com.codeberry.yws.*;

import java.io.BufferedOutputStream;
import java.io.IOException;

public class CustomContextServer {
  public static void main(String[] args) throws IOException {
    YoctoWebServer server = new YoctoWebServer(8080, new FileContextHandler("", "./content"));
    server.putContext(new SizeContextHandler("size"));
    server.start();
  }

  static class SizeContextHandler implements ContextHandler {
    private String contextPath;

    public SizeContextHandler(String contextPath) {
      this.contextPath = contextPath;
    }

    public String getContextPath() {
      return contextPath;
    }

    public Request handle(Request request, Response response) throws IOException {
      System.out.println("yserver.SizeContextHandler.handle");

      String msg = "\"" + request.getArgs().get("filename") + "\" Size " + (System.currentTimeMillis() / 1000) % 60;
      byte[] buf = msg.getBytes();
      response.setContentType("text/plain");
      response.setContentLength(buf.length);
      BufferedOutputStream out = response.ready();
      out.write(buf);
      return null;
    }
  }
}